tree grammar AlgebraGrammarEvaluator;

options {
  language = Java;
  tokenVocab = BasicAlgebraEqu;
  ASTLabelType = CommonTree;
}

@header{
	package algebra;
	import java.util.Map;
	import java.util.HashMap;
	import java.util.Random;
}

@members {
	public Map<String, Integer> variables = new HashMap<String, Integer>();
	int side = 0;
}

evaluator returns [PolynomialEquation poly]
	: p=polynomial EOF {poly = p;}
	;

polynomial returns [PolynomialEquation poly]
	: ^('+' op1=polynomial op2=polynomial) {poly = op1.add(op2, side, '+');}
	| ^('-' op1=polynomial op2=polynomial) {poly = op1.add(op2, side, '-');}
	| ^('*' op1=polynomial op2=polynomial) {poly = op1.add(op2, side, '*');}
	| ^('/' op1=polynomial op2=polynomial) {poly = op1.add(op2, side, '/');}
	| ^('^' op3=polynomial op4=polynomial) {
		poly = new PolynomialEquation(new Poly(op3.leftSide.getFirst().variable, op4.leftSide.getFirst().coefficient, 1));
	}
	| ^('=' op1=polynomial op2=polynomial){
			side = 1;
			poly = op1.add(op2, side, '\0');
		}
	| POLY {
			Random r = new Random();
			int c = r.nextInt(50) + 1;
			Poly p = new Poly('x', 1, c);
			poly = new PolynomialEquation(p);
		}
	|	POLY2	{
			Random r = new Random();
			int c = r.nextInt(50) + 1;
			Poly p = new Poly('x', 2, c);
			poly = new PolynomialEquation(p);
		}
	| IDENT {
			Poly p;
			if(variables.containsKey($IDENT.text)){
				p = new Poly('\0', 1, variables.get($IDENT.text));
			}else{
				Random randomGenerator = new Random();
				int r = randomGenerator.nextInt(50) + 1;
				variables.put($IDENT.text, r);
				p = new Poly('\0', 1, r);
			}
			poly = new PolynomialEquation(p);
		}
	|	INTEGER {
			poly = new PolynomialEquation(new Poly('\0', 1, Integer.parseInt($INTEGER.text)));
	}
	|	VARIABLE {poly = new PolynomialEquation(new Poly($VARIABLE.text.charAt(0), 1, 1));}
	;